<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Continent as ContinentModel;
/**
 * 大洲控制器
 * @package app\user\admin
 */
class Continent extends Admin
{
    /**
     * 邮件发送记录日志列表
     * @author 李洪波 <361951119@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {

        $data_list = ContinentModel::where($this->getMap())->where(['type'=>'continent'])
            ->order($this->getOrder('id DESC'))
            ->paginate();
        if($data_list->items()){
            foreach ($data_list->items() as &$val){
                $country=ContinentModel::where(['parent_id'=>$val['id'],'type'=>'country'])->count();
                $val['country']=$country;
            }
        }

        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('area')
            ->addTopButton('add',['title'=>'Add'])
            ->addRightButton('edit',['title'=>'edit'])
            ->addRightButton('delete',['title'=>'delete','data-title'=>'This data is associated with __country__ countries. Cancel the association before deleting it','data-confirm'=>'confirm','data-cancel'=>'cancel'])
//            ->addRightButton('custom',$btn_access)
            ->addColumns([
                ['id', 'ID'],
                ['name', 'Continent'],
                ['country', 'Country'],
                ['updater', 'Updater'],
                ['update_time', 'Last update time'],
                ['right_button', 'Operation', 'btn'],
            ])
            ->setRowList($data_list)
            ->setSearchArea([
                ['text', 'name', 'Continent','like'],
            ])
            ->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $data['name'] == '' && $this->error('Please fill in the Continent name');
            if(strlen($data['name'])>40) $this->error('Continent name Up to 40 characters can be entered');

            if(!$this->check($data['name'])) $this->error('Data duplicated, please re-enter');
            $list = [];
            $list['name']=$data['name'];
            $list['type']='continent';
            $list['update_time']=date('Y-m-d H:i:s');
            $list['create_time']=date('Y-m-d H:i:s');
            $list['updater']=session('user_auth')['username'];
            $continentModel = new ContinentModel();
            if (false !== $continentModel->save($list)) {
                $this->success('add success', 'index');
            } else {
                $this->error('sdd failed');
            }
        }

        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', 'Continent'],
            ])
            ->fetch();
    }


    public function edit($id = 0)
    {
        if ($id === 0) $this->error('missing parameter');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $data['name'] == '' && $this->error('Please fill in the continent name');
            if(strlen($data['name'])>40) $this->error('Continent name Up to 40 characters can be entered');
            if(!$this->check($data['name'],$id)) $this->error('Data duplicated, please re-enter');
            $data['update_time']=date('Y-m-d H:i:s');
            $data['updater']=session('user_auth')['username'];
            if (ContinentModel::update($data,['id'=>$id])) {
                $this->success('edit success', 'index');
            } else {
                $this->error('edit failed');
            }
        }
        // 获取数据
        $info = ContinentModel::get($id);

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', 'Continent'],
            ])
            ->setFormData($info)
            ->fetch();
    }

    private function check($name,$id=0){
        $id=ContinentModel::where(['name'=>$name])
            ->when($id,function ($query)use($id){
                $query->where('id','neq',$id);
            })
            ->value('id');
        if($id){
            return false;
        }else{
            return true;
        }
    }

    public function delete($record = []){
        $ids   = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $country=ContinentModel::where(['parent_id'=>$ids,'type'=>'country'])->count();
        if($country) $this->error('Please remove the associated country first, and then delete');

        ContinentModel::where(['id'=>$ids])->delete();
        $this->success('delete success','index');
    }
}
